﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using Microsoft.Office.Project.EPMAuditing.Library;
using System.IO;

namespace Microsoft.Office.Project.EPMAuditing.AuditListenerCatalog
{
    public class CSVFileAuditListener : BaseFileAuditListener
    {
        protected override string NewFileName()
        {
            return String.Format(CultureInfo.InvariantCulture, "{0}{1} {2}.csv", FileDirectory, FileBaseName,
                DateTime.Now.ToString("yyyyMMdd-HHmmss", DateTimeFormatInfo.InvariantInfo));
        }

        public override void Write(MemoryStream ms)
        {
            //ChangeRecord changeRecord = DeserializeMessage(ms);
            ChangeRecord changeRecord = new ChangeRecord(ms);
            changeRecord.TracingService = TracingService;
            string eventArgsTrimmed = string.Empty;
            string dataSetChangesTrimmed = string.Empty;

            if (changeRecord.PSEventArgs != null)
                eventArgsTrimmed = changeRecord.PSEventArgsXml.Replace(Environment.NewLine, string.Empty);

            if (changeRecord.DataSetChanges != null)
                dataSetChangesTrimmed = changeRecord.DataSetChanges.Replace(Environment.NewLine, string.Empty);

            base.WriteToFile(String.Format(CultureInfo.InvariantCulture, @"""{0}"", ""{1}"", ""{2}"", ""{3}"", ""{4}"", ""{5}"", ""{6}"", ""{7}"", ""{8}"", ""{9}"", ""{10}""",
                changeRecord.EventTime, changeRecord.EventName, changeRecord.EventSourceName,
                changeRecord.EventContextInfo.IsWindowsUser.ToString(), changeRecord.EventContextInfo.UserName,
                changeRecord.EventContextInfo.UserGuid.ToString(), changeRecord.EventContextInfo.TrackingGuid.ToString(),
                changeRecord.EventContextInfo.SiteGuid.ToString(), changeRecord.EventContextInfo.Lcid,
                eventArgsTrimmed, dataSetChangesTrimmed));
        }

        protected override void AddHeader()
        {
            base.WriteToFile(string.Format(CultureInfo.InvariantCulture, "File opened at {0}", DateTime.Now.ToString()));
            base.WriteToFile("EventTime, EventName, EventSourceName,  IsWindowsUser, UserName, UserGuid, TrackingGuid, SiteGuid, lcid, PSEventArgsXml, DataSetChanges");
        }

        protected override void AddFooter()
        {
            base.WriteToFile(string.Format(CultureInfo.InvariantCulture, "File closed at {0}", DateTime.Now.ToString()));
        }
    }
}
